<?php
class UserModel extends FW24H_Model {
	var $tableName = '24hfw_user';
	var $_primaryKey = 'user_id';

	var $Perms = '0';
	// Check username and password
	// Use for login page
	// Author: Thaodx
	function checkLogin($username, $password, $rem=0){
		$user = $this->find( 'user_name="'.$username.'" AND user_active=1', 'user_id, user_name, user_password, user_salt, user_active');
		if(sizeof($user) > 0){
			//$user[0]['user_salt'];
			$md5 = md5(md5($password).$user[0]['user_salt']);
			
			if( $md5 == $user[0]['user_password']) { // ok, dang nhap thanh cong
				if( $rem){ // neu dat no truy cap
					$key = $user[0]['user_salt'];
					$f = $user[0]['user_name'];
					$t = time();
					$t_hex = sprintf("%08x", $t);
					$m = md5($key.$f.$t_hex);
					
					setcookie( "OCM_UID", $user[0]['user_id'], time()+60*60*24*30, "/");					
					setcookie( "OCM_24HFW", $m.'%'.$t_hex, time()+60*60*24*30, "/");
				}
				return $user[0];
			}
			else{
				return -1;
			}
		}
		else{
			return -1;
		}
	}
	function addUser( $user) {
		return $this->save( $user);
	}
	
	function checkUser( $userName, $userEmail){
		$arrUser = $this->find("user_name='". $userName ."'");
		$arrEmail = $this->find("user_email='". $userEmail ."'");
		if(sizeof($arrUser) > 0){
			return 1;
		}
		elseif(sizeof($arrEmail) > 0){
			return 2;
		}
		else{
			return 0;
		}
	}
	
	function checkCookie(){
		//print_r($_COOKIE);die();
		if( isset( $_COOKIE['OCM_UID']) && isset( $_COOKIE['OCM_24HFW']) && $_COOKIE['OCM_UID'] != '' && $_COOKIE['OCM_24HFW'] != ''){
			// Get user cookie from DB
			$ck = $this->find( 'user_id='.intval($_COOKIE['OCM_UID']), 'user_name, user_id, user_password, user_salt, user_active, user_cookie');
			// User is valid?
			if(sizeof($ck) > 0){
				$arrClient = explode('%', $_COOKIE['OCM_24HFW']);
				$m = md5( $ck[0]['user_salt'].$ck[0]['user_name'].$arrClient[1]);
				$ckCreatedate = hexdec($arrClient[1]);
				if(time() - $ckCreatedate > TIME_REMEMBER_ME){
					return false;
				} else {
					if($m == $arrClient[0]){
						return $ck[0];
					}
				}
			}
			else{
				return false;
			}
		}
		
		return false;		
	}
	
	// Update user's last login
	// Author: Thaodx
	function updateLogin($arrUser, $uid){
		$this->update($arrUser, $uid);
	}
	// user logout
	// Author: Thaodx
	function userLogout(){
		
	}

	function getPerm( $menu_id, $user_id, $permission_name='read') {
		$this->_cache = false;
		$f_sql = "SELECT * FROM 24hfw_user_menu WHERE 24hfw_user_menu_user='{$user_id}' AND 24hfw_user_menu_menu='{$menu_id}' AND 24hfw_user_menu_permission='{$permission_name}'";
		$perm = $this->ExecuteOne( $f_sql);
		return $perm;
	}
}
